<template>
  <div>
    <el-form label-width="80px">
      <el-row style="margin-bottom: 10px">
        <el-cascader
          size="large"
          :options="regionData"
          v-model="selectedCity"
          @change="handleCityChange"
        >
        </el-cascader>
      </el-row>
      <el-row :gutter="20" style="margin-bottom: 10px">
        <el-col :span="18">
          <el-input
            type="text"
            v-model="addressInfo.address"
            placeholder="请输入地点"
            @change="handleAddressChange"
          >
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="" @click="searchPlace" class="btn">搜索地图</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div id="baidu-map-container" style="width: 100%; height: 400px"></div>
  </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from 'element-china-area-data';
export default {
  data() {
    return {
      selectedCity: [],
      map: null,
      // 省份数据
      regionData: regionData,
      addressInfo: {
        // 地址信息
        longitude: '', // 经度
        latitude: '', // 纬度
        province: '', // 省
        city: '', // 市
        district: '', // 区
        address: '', // 详细地址
      },
    };
  },
  props: {
    value: {
      type: Object,
      default: () => ({}),
    },
  },
  watch: {
    addressInfo: {
      handler(newVal, oldVal) {
        this.confirmMapAddress();
      },
      deep: true, // 深度监听对象的属性变化
    },
    value: {
      handler(newVal, oldVal) {
        this.addressInfo = this.value;
        this.addressTextToCode(
          this.addressInfo.province,
          this.addressInfo.city,
          this.addressInfo.district,
        );
      },
      deep: true,
    },
  },
  created() {
    this.initBaiduMap();
  },
  methods: {
    // 初始化百度地图
    initBaiduMap() {
      let that = this;
      this.$nextTick(function () {
        /** 初始化地图Start */
        // eslint-disable-next-line no-undef
        var map = new BMap.Map('baidu-map-container'); // 创建地图实例
        this.map = map;
        // eslint-disable-next-line no-undef
        var point = new BMap.Point(116.404, 39.915); // 设置中心点坐标
        map.centerAndZoom(point, 13); // 地图初始化，同时设置地图展示级别
        map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
        /** 初始化地图End */

        /** 点击地图创建坐标事件Start */
        // 添加地图点击事件
        map.addEventListener('click', function (e) {
          var clickpt = e.point; // 点击的坐标
          map.clearOverlays(); // 移除地图上的标注
          // eslint-disable-next-line no-undef
          var marker = new BMap.Marker(clickpt); // 创建标注
          map.addOverlay(marker); // 将标注添加到地图中
          // 逆地址解析
          that.geocAddress(clickpt);
        });
        /** 点击地图创建坐标事件End */
      });
    },

    searchPlace() {
      let that = this;
      that.map.clearOverlays(); // 移除地图上的标注
      // eslint-disable-next-line no-undef
      var local = new BMap.LocalSearch(that.map, {
        //智能搜索
        onSearchComplete: function (results) {
          let poi = results.getPoi(0); //获取第一个智能搜索的结果
          var searchpt = poi.point; // 获取坐标
          that.map.centerAndZoom(searchpt, 16);
          // eslint-disable-next-line no-undef
          that.map.addOverlay(new BMap.Marker(searchpt)); //添加标注
          that.geocAddress(searchpt); // 逆地址解析
        },
      });
      local.search(
        that.addressInfo.province +
          that.addressInfo.city +
          that.addressInfo.district +
          that.addressInfo.address,
      );
    },

    /** 逆向解析地址 point */
    geocAddress(point) {
      let that = this;
      // eslint-disable-next-line no-undef
      var geoc = new BMap.Geocoder();
      geoc.getLocation(point, function (geocInfo) {
        // 设置基本信息
        var addressInfo = geocInfo.addressComponents;
        that.addressInfo.longitude = point.lng + '';
        that.addressInfo.latitude = point.lat + '';
        that.addressInfo.province = addressInfo.province;
        addressInfo.city = addressInfo.city == addressInfo.province ? '市辖区' : addressInfo.city;
        that.addressInfo.city = addressInfo.city;
        that.addressInfo.district = addressInfo.district;
        that.addressTextToCode(addressInfo.province, addressInfo.city, addressInfo.district);
        let address = addressInfo.street + addressInfo.streetNumber;
        if (geocInfo.surroundingPois.length > 0) {
          address = address + geocInfo.surroundingPois[0].title;
        }
        that.addressInfo.address = address;
      });
    },

    addressTextToCode(province, city, district) {
      this.$nextTick(() => {
        let code1 = TextToCode[province].code;
        let code2 = TextToCode[province][city].code;
        let code3 = TextToCode[province][city][district].code;
        this.selectedCity = [code1, code2, code3];
      });
    },

    handleCityChange() {
      this.addressInfo.province = CodeToText[this.selectedCity[0]];
      this.addressInfo.city = CodeToText[this.selectedCity[1]];
      this.addressInfo.district = CodeToText[this.selectedCity[2]];
      this.resetPostion();
    },

    handleAddressChange() {
      this.resetPostion();
    },

    // 重置经纬度
    resetPostion() {
      this.addressInfo.latitude = '';
      this.addressInfo.longitude = '';
    },

    /**
     * 确认选择
     */
    confirmMapAddress() {
      this.$emit('input', this.addressInfo);
    },
  },
};
</script>

<style lang="scss">
// 防止地图自动完成的对象被遮挡
.tangram-suggestion {
  z-index: 9999;
}

.btn:hover {
  background-color: #3f9eff;
  color: #fff;
  border-color: #3f9eff;
}

.btn {
  color: #409eff;
  background: #ecf5ff;
  border-color: #b3d8ff;
}
</style>
